<template>
	<div style="padding:0 37px 0 44px">
    <div class="breadcrumb-father">
      <div class="new-breadcrumb">
        
        <router-link  :to="{path:'/welcome'}">
          <img src="../../../assets/imgs/Home.png" alt="">
        </router-link>
        <router-link :to="{path:'/agent'}">{{$t('agent.agent')}}</router-link>
        <span class="arrow">></span>
        <!-- <icon-svg icon-class="setting"></icon-svg> -->
        <span :title="$route.query.name">{{$route.query.name}}</span>
      </div>
    </div>

    <div class="handle_box" v-if="isModify || isAdd || showBtn || !showDetails">
        <ul class="button_box" v-if="userType!=='9' && userType !== '5' && userType !== '11' && showHandle ">
            <li class="confirm" v-if='isModify' @click='modify()'>
                <icon-svg icon-class="xiugai" class="icon-btn"></icon-svg>{{$t('button.Modify')}}
            </li>
            <li class="confirm" v-if='isAdd' @click="addAgent()">
                <icon-svg icon-class="tijiao" class="icon-btn"></icon-svg>{{ $t('button.New1') }}
            </li>
            <li class="confirm" v-show='showBtn' @click='commitModify()'>
                <icon-svg icon-class="tijiao" class="icon-btn"></icon-svg>{{ $route.query.state == '0' ? $t('button.Resubmit') : $t('button.OK') }}
            </li>
            <li class="cancel" v-show='!showDetails' @click="reset()">
                <icon-svg icon-class="quxiao" class="icon-btn"></icon-svg>{{$t('button.Cancel')}}
            </li>
        </ul><!-- button_box结束 -->
    </div><!-- handle_box结束 -->

    <!-- 防止表格层被遮挡 -->
    <div class="table-space-div" v-if="isModify || isAdd || showBtn || !showDetails"></div>

    <div class="table-div" id="one">
      <div class="title">{{$t('agent.CompanyInfo')}}</div>
      <ul class="content">
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Name')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.name" id="name" type="text" :readonly="showDetails" maxlength="100" @blur="checkBDName" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Type')}}:</div>
          </div>
          <div class="right-div">
            <input v-show="showDetails" v-model="agentData.idType" type="text" :readonly="showDetails" :class="{'view-input': showDetails}" />
            <el-select v-show="!showDetails" :placeholder="$t('placeH.Please')" @change="selectIdType" v-model.lazy="idType" clearable :readonly="showDetails">
              <el-option :value="$t('mer.LimitedCompany')"></el-option>
              <el-option :value="$t('mer.Partnership')"></el-option>
              <el-option :value="$t('mer.SoleProprietor')"></el-option>
            </el-select>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Address')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.address" id="address" type="text" :readonly="showDetails" maxlength="200" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.MailAddr')}}:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.mailingAddress" type="text" :readonly="showDetails" maxlength="200" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('mer.BRNo')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.registrationNumber" id="registrationNumber" type="text" :readonly="showDetails" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" maxlength="20" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Contact')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.contacts" id="contacts" type="text" :readonly="showDetails" maxlength="50" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont" v-if="companyId=='2'">{{$t('mec.Email')}}*:</div>
            <div class="cont" v-else>{{$t('mec.Email')}}:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.email" id="email" :readonly="showDetails" maxlength="100" @blur="valiEmail()" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont" v-if="companyId=='2'">{{$t('agent.PhoneNo')}}:</div>
            <div class="cont" v-else>{{$t('agent.PhoneNo')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.phone" id="phone" type="text" :readonly="showDetails" @blur="checkBDPhone" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" maxlength="20" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.MobileNo')}}*:</div>
          </div>
          <div class="right-div">
              <input v-model.lazy.trim="agentData.telephone" id="telephone" type="text" :readonly="showDetails" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" maxlength="20" :class="{'view-input': showDetails}" />
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('search.UpperLevel1')}}*:</div>
          </div>
          <div class="right-div">
            <input v-show="showDetails" v-model="agentData.parentName" id="parentName" type="text" :readonly="showDetails" :class="{'view-input': showDetails}" />

            <el-select v-show="!showDetails" v-model.lazy="agentData.parentName" @change='selectId()' @clear='clearSel' clearable :placeholder="$t('placeH.Please')" :readonly="showDetails">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.UpperLevelID')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.parentNumber" id="parentNumber" type="text" disabled="true" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
      </ul><!-- content结束 -->
      <!-- <div class="circle-title">Shop photos</div> -->
    </div><!-- table-div结束 -->

    <div class="table-div" id="two" v-show="showOtherInfo">
      <div class="title">{{$t('mec.SettlementInfo')}}</div>
      <ul class="content">
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Method')}}*:</div>
          </div>
          <div class="right-div">
            <input v-show="showDetails" v-model="clearingMode" id="clearingMode" type="text" :readonly="showDetails" :class="{'view-input': showDetails}" />

            <el-select v-show="!showDetails" :placeholder="$t('placeH.Please')" v-model.lazy="agentData.clearingMode" clearable :readonly="showDetails">
              <el-option :label="$t('cash.check')" value="0"></el-option>
              <el-option :label="$t('cash.onlineBanking')" value="1"></el-option>
            </el-select> 
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('mer.BankName')}}*:</div>
          </div>
          <div class="right-div">
            <input v-model.lazy.trim="agentData.bankname" id="bankname" type="text" :readonly="showDetails" maxlength="100" autocomplete="off" :class="{'view-input': showDetails}" />
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('mer.BankCode1')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.bankCode" id="bankCode" type="text" :readonly="showDetails" maxlength="6" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\-]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('mer.AccountName')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.drawname" id="drawname" type="text" :readonly="showDetails" maxlength="100" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('mer.AccountNo')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.bankaccount" id="bankaccount" type="text" :readonly="showDetails" maxlength="20" autocomplete="off" oninput="this.value=this.value.replace(/[^\d]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">SWIFT:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.SWIFTcode" type="text" :readonly="showDetails" maxlength="20" autocomplete="off" :class="{'view-input': showDetails}" /></div>
        </li>
      </ul><!-- content结束 -->
      <!-- <div class="circle-title">Shop photos</div> -->
    </div><!-- table-div结束 -->

    <div class="table-div" id="three" v-show="showOtherInfo">
      <div class="title">{{$t('agent.CommissionInfo')}}</div>
      <ul class="content">
        <li class="item">
          <div class="left-div">
            <div class="cont">POS{{ currency }}*:</div>
          </div>
          <div class="right-div">
            <input v-model.lazy.trim="agentData.posMachine" id="posMachine" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" />
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.Scanner')+ currency}}*:</div>
          </div>
          <div class="right-div">
            <input v-model.lazy.trim="agentData.scanner" id="scanner" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" />
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.SubscriptionFee')+ currency}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.franchiseFee" id="franchiseFee" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.OfflineBase')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.lineBaseRate" id="lineBaseRate" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.OnlineBase')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.onLineBaseRate" id="onLineBaseRate" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.OfflineComm')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.lineBrokerage" id="lineBrokerage" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.OnlineComm')}}*:</div>
          </div>
          <div class="right-div"><input v-model.lazy.trim="agentData.onLineBrokerage" id="onLineBrokerage" maxlength="5" type="text" :readonly="showDetails" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" /></div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.EndDate')}}:</div>
          </div>
          <div class="right-div date-input">
            <input v-show="showDetails" v-model="agentData.shutDownDate" type="text" :readonly="showDetails" :class="{'view-input': showDetails}" />

            <el-date-picker v-show="!showDetails" v-model.lazy="agentData.shutDownDate" style="width:100%;" :placeholder="$t('placeH.Please')" :editable=false clearable type="date" :readonly="showDetails"></el-date-picker>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('AuMer.SettlementPeriod')}}*:</div>
          </div>
          <div class="right-div">
            <input v-show="showDetails" type="text" v-model="settlementCycle" id="settlementCycle" :readonly="showDetails" :class="{'view-input': showDetails}" />

            <el-select v-show="!showDetails" :placeholder="$t('placeH.Please')" v-model.lazy="agentData.settlementCycle" clearable :readonly="showDetails">
              <el-option v-if="companyId=='2'" value='1' label="T+1"></el-option>
              <el-option value='2' label="T+2"></el-option>
              <el-option value='3' label="T+3"></el-option>
              <el-option value='4' label="T+4"></el-option>
              <el-option value='5' label="T+5"></el-option>
              <el-option value='6' label="T+6"></el-option>
              <el-option value='7' label="T+7"></el-option>
            </el-select>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('salesman.Salesman')}}*:</div>
          </div>
          <div class="right-div">
            <input v-show="showDetails" v-model="agentData.salesmanName" id="salesmanName" type="text" :readonly="showDetails" :class="{'view-input': showDetails}" />

            <el-select v-show="!showDetails" v-model.lazy="agentData.salesmanName" id="salesmanName" @change='selectSalesman()' clearable :placeholder="$t('placeH.Please')" :readonly="showDetails">
              <el-option v-for="item in selectSalesmanData" :label="item.salesmanName" :value="item.salesmanName" :key="item.id">
              </el-option>
            </el-select>
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.BDStaffNo')}}*:</div>
          </div>
          <div class="right-div">
            <input v-model.lazy.trim="agentData.salesmanNumber" id="salesmanNumber" type="text" disabled="true" :class="{'view-input': showDetails}" />
          </div>
        </li>
        <li class="item">
          <div class="left-div">
            <div class="cont">{{$t('agent.commissionRatio')}}:</div>
          </div>
          <div class="right-div">
            <input v-model.lazy.trim="agentData.proportion" type="text" :readonly="showDetails" maxlength="5" autocomplete="off" oninput="this.value=this.value.replace(/[^\d\.]/g,'')" :class="{'view-input': showDetails}" />
          </div>
        </li>
      </ul><!-- content结束 -->
      <!-- <div class="circle-title">Shop photos</div> -->
    </div><!-- table-div结束 -->

    <p v-show="showChargeInfo"> {{ $t('agent.hintInfo') }} </p>

    <div style="height: 100px;"></div>

	</div>
</template>

<script>
import {
  createAgent,
  agentDetails,
  modifyAgent,
  salesmanAll,
  salesmanAdd,
  querySuperiorAgent,
  modifySalesman,
  validateBDName,
  validateBDPhone,
  validateBDNameModify,
  validateBDPhoneModify,
  validateBDEamil,
  validateBDEamilModify
} from "api/merchant/agent/index";
export default {
  name: "agent",
  data() {
    return {
      parentDistributorId: "",
      isAdd: this.$route.query.id == '1' ? true : false, //新增按钮显示或隐藏 根据父组件传递的id判断
      isModify: this.$route.query.id == '2' ? true : false, //修改按钮显示或隐藏 根据父组件传递的id判断
      showDetails: this.$route.query.id == '1' ? false : true,
      showBtn: false,
      agentData: {
        name: undefined,
        idType: undefined,
        address: undefined,
        mailingAddress: undefined,
        registrationNumber: undefined,
        contacts: undefined,
        email: undefined,
        phone: undefined,
        telephone: undefined,
        parentName: undefined,
        parentNumber: undefined,
        clearingMode: undefined,
        bankname: undefined,
        bankaccount: undefined,
        drawname: undefined,
        SWIFTcode: undefined,
        posMachint: undefined,
        scanner: undefined,
        franchiseFee: undefined,
        lineBaseRate: undefined,
        onLineBrokerage: undefined,
        lineBrokerage: undefined,
        onLineBrokerage: undefined,
        shutDownDate: undefined,
        salesmanName: undefined,
        salesmanNumber: undefined,
        proportion: undefined,
        password: undefined,
        debId: undefined,
        salesmanId: undefined,
        salesmanName:undefined,
        settlementCycle:undefined,
      },
      settlementCycle:undefined,
      options: [],
      selectSalesmanData: [],
      companyId: localStorage.getItem("companyId"),
      userType: localStorage.getItem("userType"),
      selDistributorId: localStorage.getItem("distributorId"),
      grade: localStorage.getItem("grade"),
      showHandle: true ,
      showOtherInfo:true,
      showChargeInfo:false,
      selAgentObj: {},
      HkAgentRequiredArr: [
        "name",
        "address",
        "registrationNumber",
        "contacts",
        "phone",
        "telephone",
        "parentName",
        "parentNumber",
        "clearingMode",
        "bankname",
        "bankCode",
        "drawname",
        "bankaccount",
        "posMachine",
        "scanner",
        "franchiseFee",
        "lineBaseRate",
        "onLineBaseRate",
        "lineBrokerage",
        "onLineBrokerage",
        "settlementCycle",
        "salesmanName",
        "salesmanNumber",
      ],
      AuAgentRequiredArr: [
        "name",
        "address",
        "registrationNumber",
        "contacts",
        "telephone",
        "parentName",
        "parentNumber",
        "clearingMode",
        "bankname",
        "bankCode",
        "drawname",
        "bankaccount",
        "posMachine",
        "scanner",
        "franchiseFee",
        "lineBaseRate",
        "onLineBaseRate",
        "lineBrokerage",
        "onLineBrokerage",
        "email",
        "settlementCycle",
        "salesmanName",
        "salesmanNumber",
      ],
      HKNoFirstAgentRequireArr:[
        "name",
        "address",
        "registrationNumber",
        "contacts",
        "phone",
        "telephone",
        "parentName",
        "parentNumber",
      ],
      AuNoFirstAgentRequireArr:[
        "name",
        "address",
        "registrationNumber",
        "contacts",
        "telephone",
        "parentName",
        "parentNumber",
      ],
      requiredArr:[],
      unwantedArr:[
        "clearingMode",
        "bankname",
        "bankCode",
        "drawname",
        "bankaccount",
        "SWIFTcode",
        "posMachine",
        "scanner",
        "franchiseFee",
        "lineBaseRate",
        "onLineBaseRate",
        "lineBrokerage",
        "onLineBrokerage",
        "settlementCycle",
        "salesmanName",
        "salesmanNumber",
      ],
      flag: false,
      clearingMode: "",
      salesmanId: null,
      idType:undefined,
      modifyFlag:false,
      currency:'',
    };
  },
  watch:{
    'agentData.parentName':function(newVal,oldVal){
      if ( newVal == '') this.agentData.parentId = undefined;
    },
    'agentData.salesmanName':function(newVal,oldVal){
      if ( newVal == '') this.agentData.salesmanNumber = undefined;
    },
  },
  created() {
    if (this.$route.query.state == "1") {
      this.isModify = false;
    }
    if (this.$route.query.state == "0") {
    }
    if (this.userType == "2" ) {
      if(this.grade !== '0'){
        this.selAgentObj.distributorId = this.selDistributorId;
        this.getSuperiorAgent(this.selAgentObj);
      } else {
        this.selAgentObj.companyId = this.companyId;
        this.getSuperiorAgent(this.selAgentObj);
      } 
    } 
    if (this.$route.query.id == '2') {
      this.getAgentDetails(this.$route.query.disId);
      this.showOtherInfo = this.$route.query.grade > 1 ? false : true;
    } else {
      this.showOtherInfo = this.$route.query.grade >= 1 ? false : true;
    }
    if( this.showOtherInfo ){
      salesmanAll({companyId:this.companyId}).then(res => {
        this.selectSalesmanData = res.value;
      });
    }

    if( this.$route.query.id == '2' && this.userType == "2" ){
      this.showHandle = localStorage.getItem("distributorId") ==  this.$route.query.parentId ? true : false;
      if( localStorage.getItem("grade") == 0 ){
        this.showHandle = true;
      }
    }
    setTimeout(function(){
        $("#agent").addClass("is-active");
    },500);

    if (this.companyId == '1') this.currency = 'HK$ ';
    if (this.companyId == '2') this.currency = 'A$ ';
  },
  beforeRouteLeave(to,from, next){
    if(to.path == '/agent'){
      next();
    } else {
      $("#z_businessManagement .el-menu a li:eq(1)").removeClass('is-active');
      localStorage.removeItem('searchAgentData');
      next();
    }
  },
  updated(){
    $(".border-red").removeClass('border-red');
  },
  methods: {
    reset(){
      if(this.$route.query.id=='2'){
        this.showDetails = true;
        this.showBtn = false;
        this.isModify = true;
        this.agentData = JSON.parse(localStorage.getItem('agentData'));
      } else {
        // this.$router.push({ path: "/agent",query:{ page:this.$route.query.page,pageSize: this.$route.query.pageSize } });
        this.$router.push({ path: "/agent" });
      }
    },
    // 验证邮箱格式
    valiEmail(){
      const reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
      if( !this.agentData.email ){
        return false;
      } else if( !reg.test(this.agentData.email) ){
          this.$message( this.$t('hint.EmailFormatIncorrect') );
          this.agentData.email = "";
          return;
      } 
      if( this.companyId == '2'){
        if( this.$route.query.id == '1' ){
          validateBDEamil( this.agentData.email ).then(res=>{
            if(res.code == 0 ){
              return false;
            } else {
              this.agentData.email = "";
              this.$message( this.$t('hint.EmailAlreadyExists') );
            } 
          })
        } else {
          validateBDEamilModify( this.agentData.email,this.$route.query.disId ).then(res=>{
            if(res.code == 0){
              return false;
            } else {
              this.agentData.email = "";
               this.$message( this.$t('hint.EmailAlreadyExists') );
            } 
          })
        }
      }
    },
    // 验证代理商名称
    checkBDName(){
      if(!this.agentData.name) return false;
      if(this.$route.query.id == '1'){
        validateBDName(this.agentData.name).then(res=>{ 
          if( res.code == 0 ){
            return false;
          } else {
            this.$message( this.$t('hint.CompanyNameAlreadyExists') );
            this.agentData.name = '';
          }
        })
      } else {
        validateBDNameModify(this.agentData.name,this.$route.query.disId).then(res=>{ 
          if(res.code == 0){
            return false;
          } else {
            this.$message( this.$t('hint.CompanyNameAlreadyExists') );
            this.agentData.name = '';
          }
        })
      }
    },
    // 验证代理商电话
    checkBDPhone(){
      if( this.companyId == '1' ){
        if(this.$route.query.id == '1'){
          validateBDPhone(this.agentData.phone).then(res=>{
            if(res.code == 0){
              return false;
            } else {
              this.$message( this.$t('hint.PhoneNumberAlreadyExists1') );
              this.agentData.phone = '';
            }
          })
        } else {
          validateBDPhoneModify(this.agentData.phone,this.$route.query.disId).then(res=>{
            if(res.code == 0){
              return false;
            } else {
              this.$message( this.$t('hint.PhoneNumberAlreadyExists1') );
              this.agentData.phone = '';
            }
          })
        }
      }
    },
    //选择类型
    selectIdType(val){
      this.$set(this.agentData,'idType',val);
    },
    selectSalesman() {
      for (let i = 0; i < this.selectSalesmanData.length; i++) {
        if ( this.selectSalesmanData[i].salesmanName == this.agentData.salesmanName ) {
          this.agentData.salesmanId = this.selectSalesmanData[i].id;
          this.agentData.salesmanNumber = this.selectSalesmanData[i].salesmanNumber;
        }
      }
    },
    // 选择上级代理商
    selectId() {
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].name == this.agentData.parentName) {
          this.agentData.parentId = this.options[i].id;
          this.agentData.parentNumber = this.options[i].distributorNumber;
          this.parentDistributorId = this.options[i].id;
          this.showOtherInfo = this.options[i].grade == 0 ? true : false;
          this.showChargeInfo = this.options[i].grade == 0 ? true : false;
          this.agentData.grade = this.options[i].grade + 1;
        }
      }
    },
    //清空当前选择的上级代理商
    clearSel(){
      this.showChargeInfo = fase;
    },
    getSuperiorAgent(data) {
      querySuperiorAgent(data).then(res => {
        //					console.log(res);
        this.options = res.value;
      });
    },
    getAgentDetails(id) {
      agentDetails(id)
        .then(res => {
          this.agentData = res.value;
          this.agentData.settlementCycle = this.agentData.settlementCycle.toString();
          // console.log("----该代理商详情---");
          // console.log(res);
          if( this.agentData.settlementCycle == 1 ){
            this.settlementCycle = 'T+1'
          } else if ( this.agentData.settlementCycle == 2 ){
            this.settlementCycle = 'T+2'
          } else if ( this.agentData.settlementCycle == 3 ){
            this.settlementCycle = 'T+3'
          } else if ( this.agentData.settlementCycle == 4 ){
            this.settlementCycle = 'T+4'
          } else if ( this.agentData.settlementCycle == 5 ){
            this.settlementCycle = 'T+5'
          } else if ( this.agentData.settlementCycle == 6 ){
            this.settlementCycle = 'T+6'
          } else if ( this.agentData.settlementCycle == 7 ){
            this.settlementCycle = 'T+7'
          }
          if (this.agentData.clearingMode == "0") {
            this.clearingMode = this.$t("cash.check");
          }
          if (this.agentData.clearingMode == "1") {
            this.clearingMode = this.$t("cash.onlineBanking");
          }

          this.idType = this.agentData.idType;
        })
        .catch(error => {});
    },
    //新增代理商取消按钮
    // cancel() {
    //   if (this.id == 1) {
    //     this.$emit("agentManageChange");
    //   } else if (this.state == "1") {
    //     this.$emit("agentManageChange");
    //   } else {
    //       this.showDetails = true;
    //       this.showBtn = false;
    //       this.isModify = true;
    //       this.$emit("agentManageChange");
    //   }
    // },
    //修改按钮
    modify() {
      this.showDetails = false;
      this.showBtn = true;
      this.isModify = false;
      localStorage.setItem('agentData',JSON.stringify(this.agentData));
      this.selectId();
    },
    //代理商修改确定按钮
    commitModify() {
      const _that = this;
      // [...this.requiredArr] = this.companyId == "2" ? this.AuAgentRequiredArr : this.HkAgentRequiredArr;
      if( this.companyId == "2" ){
        [...this.requiredArr] = this.agentData.grade <= 1 ? this.AuAgentRequiredArr : this.AuNoFirstAgentRequireArr; 
      } else {
        [...this.requiredArr] = this.agentData.grade <= 1 ? this.HkAgentRequiredArr : this.HKNoFirstAgentRequireArr;
      }
      const reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/; 
      if(this.agentData.email){
        if( !reg.test(this.agentData.email) ){
          this.$message( this.$t('hint.EmailFormatIncorrect') );
          return false;
        }
      }
      for (let i = 0; i < this.requiredArr.length; i++) {
        if ( this.agentData[this.requiredArr[i]] == "" || this.agentData[this.requiredArr[i]] == null || this.agentData[this.requiredArr[i]] == undefined ) {
          let prer_html =  $("#" + _that.requiredArr[i]).parent().prev().children().html();
          if(localStorage.getItem('locale') == 'en' ){
            prer_html = prer_html.replace('*','').toLocaleLowerCase();
          } else {
            prer_html = prer_html.replace('*','');
          }         
          $("#" + _that.requiredArr[i]).addClass('border-red');
          this.$message( this.$t('hint.pleaseEnter') + prer_html );
          return false;
        } else {
          this.modifyFlag = true;
        }
      }
      
      if( !this.showOtherInfo ){
        for(let i=0;i<this.unwantedArr.length;i++){
          this.agentData[this.unwantedArr[i]] = null;
        }
      }

      if(this.modifyFlag){
        if (this.$route.query.state == "0") {
          this.agentData.state = 4;
        }
        const hintAgentMsg =
          this.$route.query.state == "0"
            ? this.$t("hint.SureToAddThisAgent")
            : this.$t("hint.SureToChangeInfoOfTheAgent");
        this.$msgbox({
          title: this.$t("hint.Alert"),
          message: hintAgentMsg,
          showClose: false,
          closeOnClickModal:false,
          showCancelButton: true,
          confirmButtonText: this.$t("button.OK"),
          cancelButtonText: this.$t("button.Cancel")
        })
          .then(() => {
            modifyAgent(this.agentData).then(res => {
              this.modifyFlag = false;
              if (res.code == 0) {
                this.$msgbox({
                  title: this.$t("hint.Alert"),
                  message: this.$t("hint.SubmittedApprovalPending"),
                  showClose: false,
                  closeOnClickModal:false,
                  showCancelButton: false,
                  confirmButtonText: this.$t("button.OK"),
                  cancelButtonText: this.$t("button.Cancel"),
                  customClass:'single-msg-box',
                }).then(() => {
                    this.$router.push({ path: "/agent" });
                  })
                  .catch(() => {
                    this.agentData = res.value;
                  });
              } else {
                this.$notify({
                  title: this.$t("hint.Fail"),
                  message: this.$t("hint.FailToEdit"),
                  type: "error",
                  duration: 2000
                });
              }
            });
          })
          .catch(() => {
            done();
          });
      }
    },
    //新增代理商
    addAgent() {
      const _that = this;
      // [...this.requiredArr] = this.companyId == "2" ? this.AuAgentRequiredArr : this.HkAgentRequiredArr;
      if( this.companyId == "2" ){
        [...this.requiredArr] = this.agentData.grade <= 1 ? this.AuAgentRequiredArr : this.AuNoFirstAgentRequireArr; 
      } else {
        [...this.requiredArr] = this.agentData.grade <= 1 ? this.HkAgentRequiredArr : this.HKNoFirstAgentRequireArr;
      }
      for (let i = 0; i < this.requiredArr.length; i++) {
        if ( this.agentData[this.requiredArr[i]] == "" || this.agentData[this.requiredArr[i]] == null || this.agentData[this.requiredArr[i]] == undefined ) {
          // let prer_html =  _that.requiredArr[i] == 'settlementCycle' ? $("#" + _that.requiredArr[i]).parent().parent().parent().prev().html() : $("#" + _that.requiredArr[i]).parent().prev().html();
          let prer_html =  $("#" + _that.requiredArr[i]).parent().prev().children().html();
          if(localStorage.getItem('locale') == 'en' ){
            prer_html = prer_html.replace('*','').toLocaleLowerCase();
          } else {
            prer_html = prer_html.replace('*','');
          }         
          $("#" + _that.requiredArr[i]).addClass('border-red');
          console.log(prer_html);
          this.$message( this.$t('hint.pleaseEnter') + prer_html );
          return false;
        }
      }

      if( !this.showOtherInfo ){
        for(let i=0;i<this.unwantedArr.length;i++){
          this.agentData[this.unwantedArr[i]] = null;
        }
      }

      const reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
      if( this.agentData.email ){
        if( !reg.test(this.agentData.email) ){
          this.$message( this.$t('hint.EmailFormatIncorrect') );
          return false;
        } else {
          this.flag = true;
        }
      } else {
        this.flag = true;
      }
      if (this.flag) {
        this.$msgbox({
          title: this.$t("hint.Alert"),
          message: this.$t("hint.SureToAddThisAgent"),
          showClose: false,
          closeOnClickModal:false,
          showCancelButton: true,
          confirmButtonText: this.$t("button.OK"),
          cancelButtonText: this.$t("button.Cancel")
        }).then(() => {
          //			        console.log("确定");
          if (localStorage.getItem("distributorId")) {
            this.agentData.distributorId = localStorage.getItem("distributorId");
          }
          this.agentData.companyId = localStorage.getItem("companyId");
          createAgent(this.agentData).then(res => {
            this.flag = false;
              if (res.code == 0) {
                this.$notify({
                  title: this.$t("hint.Success"),
                  message: this.$t("hint.CreateOK"),
                  type: "success",
                  duration: 2000
                });
                this.$router.push({ path: "/agent" });
              } else if (res.code == 40005001) {
                this.$notify({
                  title: this.$t("hint.Fail"),
                  message: this.$t("hint.CompanyNameAlreadyExists"),
                  type: "error",
                  duration: 2000
                });
              } else if (res.code == 40004002) {
                this.$notify({
                  title: this.$t("hint.Fail"),
                  message: this.$t("hint.PhoneNumberAlreadyExists"),
                  type: "error",
                  duration: 2000
                });
              } else {
                this.$notify({
                  title: this.$t("hint.Fail"),
                  message: this.$t("hint.CreateFailed"),
                  type: "error",
                  duration: 2000
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        });
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.el-table::before {
  height: 0;
}
.border-red{
  border:1px solid red;
}
</style>